package cn.itcast.pinyougou.task;

import cn.itcast.pinyougou.mapper.TbSeckillGoodsMapper;
import cn.itcast.pinyougou.pojo.TbSeckillGoods;
import cn.itcast.pinyougou.pojo.TbSeckillGoodsExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class SeckillGoodsToRedisTask {

    @Autowired
    private TbSeckillGoodsMapper tbSeckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Scheduled(cron="0/30 * * * * ?")
    public void importToRedis(){
        //System.out.println("定时任务执行了："+new Date());
        //1:查询合法的秒杀商品数据：状态位为1（status=1），库存量>0，（stockCount>0），秒杀开始时间<当前时间<秒杀结束时间;
        TbSeckillGoodsExample example = new TbSeckillGoodsExample();
        TbSeckillGoodsExample.Criteria criteria = example.createCriteria();
        Date date = new Date();
        criteria.andStatusEqualTo("1")
                .andStockCountGreaterThan(0)
                .andStartTimeLessThanOrEqualTo(date)
                .andEndTimeGreaterThan(date);
        List<TbSeckillGoods> tbSeckillGoodsList = tbSeckillGoodsMapper.selectByExample(example);

        //2：将数据存入redis
        for(TbSeckillGoods good : tbSeckillGoodsList){
            redisTemplate.boundHashOps(TbSeckillGoods.class.getSimpleName()).put(good.getId(),good);
        }
    }
}
